/**
 * 获取API令牌脚本 (ESM版本)
 * 用于获取和缓存API访问令牌
 */

import fs from 'fs';
import path from 'path';
import https from 'https';
import http from 'http';
import { fileURLToPath } from 'url';

// 获取当前文件目录
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 常量定义
const TOKEN_CACHE_DIR = path.resolve(__dirname, '../.cache');
const TOKEN_CACHE_FILE = path.join(TOKEN_CACHE_DIR, 'token.json');
const TOKEN_LIFETIME = 24 * 60 * 60 * 1000; // 令牌有效期24小时

// 加载配置
const loadConfig = () => {
    try {
        const configPath = path.join(__dirname, 'env.config');
        const content = fs.readFileSync(configPath, 'utf8');
        const config = {};

        content.split('\n').forEach(line => {
            if (line.trim().startsWith('#') || !line.trim()) return;

            const match = line.match(/^([A-Z0-9_]+)="([^"]*)"/);
            if (match) {
                const [, key, value] = match;
                config[key] = value;
            }
        });

        return config;
    } catch (error) {
        console.error('加载配置文件失败:', error);
        process.exit(1);
    }
};

// 发送HTTP请求
const sendRequest = (url, method, body = null) => {
    return new Promise((resolve, reject) => {
        const parsedUrl = new URL(url);
        const options = {
            hostname: parsedUrl.hostname,
            port: parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80),
            path: parsedUrl.pathname + parsedUrl.search,
            method: method,
            headers: {
                'Content-Type': 'application/json;charset=UTF-8',
                'Accept': 'application/json, text/plain, */*',
                'Cache-Control': 'no-cache',
                'isToken': 'false'
            }
        };

        const client = parsedUrl.protocol === 'https:' ? https : http;

        const req = client.request(options, (res) => {
            let data = '';

            res.on('data', (chunk) => {
                data += chunk;
            });

            res.on('end', () => {
                try {
                    const responseData = data ? JSON.parse(data) : {};
                    if (res.statusCode >= 200 && res.statusCode < 300) {
                        resolve(responseData);
                    } else {
                        reject(new Error(`HTTP错误: ${res.statusCode}`));
                    }
                } catch (error) {
                    reject(new Error(`解析响应失败: ${error.message}`));
                }
            });
        });

        req.on('error', (error) => {
            reject(new Error(`请求失败: ${error.message}`));
        });

        if (body) {
            req.write(JSON.stringify(body));
        }

        req.end();
    });
};

// 获取令牌
const getToken = async (config, forceRefresh = false) => {
    // 确保缓存目录存在
    if (!fs.existsSync(TOKEN_CACHE_DIR)) {
        fs.mkdirSync(TOKEN_CACHE_DIR, { recursive: true });
    }

    // 检查缓存是否存在且有效
    if (!forceRefresh && fs.existsSync(TOKEN_CACHE_FILE)) {
        try {
            const tokenData = JSON.parse(fs.readFileSync(TOKEN_CACHE_FILE, 'utf8'));
            const now = Date.now();

            // 如果令牌未过期，直接返回
            if (tokenData.expireTime && tokenData.expireTime > now) {
                console.log('使用缓存的令牌');
                return tokenData.token;
            }

            console.log('缓存的令牌已过期，需要刷新');
        } catch (error) {
            console.error('读取令牌缓存失败:', error.message);
        }
    }

    // 从API获取新令牌
    try {
        console.log('从API获取新令牌...');

        // 构建请求URL和参数
        const baseUrl = config.AUTO_API_BASE_URL;
        const projectId = config.PROJECT_ID;
        const url = `${baseUrl}/get_token`;

        // 使用正确的请求体格式: {"id": "PROJECT_ID"}
        const body = { id: projectId };

        // 发送请求
        const response = await sendRequest(url, 'POST', body);

        // 检查响应
        if (response && response.token) {
            const token = response.token;
            const expireTime = Date.now() + TOKEN_LIFETIME;

            // 保存令牌到缓存
            const tokenData = {
                token,
                expireTime,
                projectId,
                createdAt: new Date().toISOString()
            };

            fs.writeFileSync(TOKEN_CACHE_FILE, JSON.stringify(tokenData, null, 2));
            console.log('令牌已获取并缓存');

            // 创建简化的token文件供cli.sh等脚本使用
            fs.writeFileSync(path.join(__dirname, 'token.json'), JSON.stringify({ token }, null, 2));
            console.log('令牌已保存到token.json文件');

            return token;
        } else {
            throw new Error('响应中没有找到有效的令牌');
        }
    } catch (error) {
        console.error('获取令牌失败:', error.message);
        throw error;
    }
};

// 主函数
const main = async () => {
    const forceRefresh = process.argv.includes('--refresh');
    const config = loadConfig();

    console.log(`API基础URL: ${config.AUTO_API_BASE_URL}`);
    console.log(`项目ID: ${config.PROJECT_ID}`);
    console.log(`强制刷新: ${forceRefresh ? '是' : '否'}`);

    try {
        const token = await getToken(config, forceRefresh);
        console.log('令牌获取成功');
        return 0;
    } catch (error) {
        console.error('获取令牌失败:', error.message);
        return 1;
    }
};

// 执行主函数
main().then(exitCode => {
    process.exit(exitCode);
}).catch(error => {
    console.error('执行过程中发生错误:', error);
    process.exit(1);
}); 